package com.experiment.aicommunityback.controller;

import com.alibaba.fastjson.JSON;
import com.experiment.aicommunityback.entity.Result;
import com.experiment.aicommunityback.entity.Role;
import com.experiment.aicommunityback.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.experiment.aicommunityback.entity.ResultCodeEnum.*;

/**
 * @author 杨婉汐
 * @name RoleController
 * @Date 2024/12/21  17:36
 */
@CrossOrigin()
@RestController
@RequestMapping("/home")
public class RoleController {
    RoleService roleService;

    @Autowired
    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 查询权限表,展示所有权限
     * <br>
     * 且展示查询权限角色个数
     */
    @GetMapping("/roleList")
    public Result showRole() {
        List<Role> allRole = roleService.allRole();
        List<HashMap<String, Integer>> roleNumber = roleService.roleNum();
        if (!allRole.isEmpty()) {
            return Result.ok().data("allRole", allRole).data("roleNumber", roleNumber);
        } else {
            return Result.setResult(UNKNOWN_ROLE_ERROR);
        }
    }

    /**
     * 根据Id或Name查询
     */
    @PostMapping("/queryRole")
    public Result queryRole(@RequestParam String idOrName) {
        if (roleService.queryRole(idOrName) != null) {
            return Result.ok().data("qureyRole", roleService.queryRole(idOrName))
                    .data("roleNumber",roleService.roleNum());
        }
        // 返回用户找不到
        return Result.setResult(UNKNOWN_ROLE_ERROR);
    }

    /**
     *  新增权限角色
     * */
    @PostMapping("/addRole")
    public Result addRole(@RequestBody String jsonText) {
        Role role = JSON.parseObject(jsonText, Role.class);
        return roleService.addRole(role);
    }


    /**
     * 更改权限
     * */
    @PostMapping("/upRole")
    public Result updatedRole(@RequestBody String jsonText) {
        Role role = JSON.parseObject(jsonText, Role.class);
        return roleService.updatedRole(role);
    }
    @PostMapping("/updatedRoleStatus")
    public Result updatedRoleStatus(@RequestBody Map<String, Object> paramMap) {
        roleService.updatedRoleStatus(paramMap);
        return null;

    }
    /**
     * 删除权限
     */
    @PostMapping("/deleteRole")
    public Result deleteRole(@RequestParam String id) {
        return roleService.deleteRole(Integer.parseInt(id));
    }
}
